const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);
const sdate = require('silly-datetime');

const {
    getTaskPage,
    wxpusher,
} = require('./old2/ti_scan_config');

const {
    readTask,
} = require('./old2/ti_logic_read_task');

const {
    logger,
    sleep,
    httpGet,
    httpPost,
    getProxy,
    getIp,
    httpProxyGet,
} = require('./old2/util');

const {
    get,
    easyPushWechatMsg,
    lpush,
    set,
    hget,
    hset,
    expire,
    hgetall,
    randBetween,
    avoidNoticeFreq,
    avoidNoticeFreqCookie,
} = require('./util');

const {
    syncExec,
    syncExec2
} = require('./model'); 

process.on('unhandledRejection', error => {
    //...不处理...
});

const serialMap = {};//已启动到任务

let ip_list = [];

let arguments = process.argv.splice(2);

let g_cookie = '';

const getTiCookieByName = name => {
    const reg = new RegExp(name+'=([^;]+);');
    const result = g_cookie.match(reg);
    return result[1] ? result[1] : '';
}


//每N秒重新拉取任务列表
(async () => {
    const url = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn=';

      try {

          const serial = 'INA849DR';

          const stock = 1;

          const cookie = await get('ti_worker_cookie');
          g_cookie = cookie;
          const arr = cookie.split(';');
          let chromeVer = 95;
          let ua;
          let platform = '"Windows"';
          arr.map(str => {
              str = str.trim();
              const key = str.substr(0, str.indexOf('='));
              const value = decodeURIComponent(str.substr(str.indexOf('=')+1));
              if (key == 'ti_ua') {//获取ua
                  ua = value;
                  try {
                      chromeVer = ua.match(/Chrome\/(\d+)/)[1];
                  } catch(e){}
      
                  if (ua.indexOf('Mac') > -1) {
                      platform = '"macOS"';
                  }
              }
          });
          const postData = JSON.stringify({
              'cartRequestList':[{
                  'opnId':serial,
                  'packageOption':null,
                  'quantity':Number(stock),
                  'sparam':'',
                  'tiAddtoCartSource':'store-pdp',
              }],
              'currency':'CNY',
          });

          const referer = `https://www.ti.com.cn/store/ti/zh/p/product/?p=${encodeURIComponent(serial)}`;

          const cmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    -d '${postData}' \
                    https://www.ti.com.cn/occservices/v2/ti/addtocart`;

          ret = await syncExec(cmdStr);

          if (ret.indexOf('cartId') > -1) {
              const msg = `全查方案：${serial}加购物车${stock}成功`;
              logger(msg);
          }else if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }

          const _ticdt = new Buffer(parseInt(new Date().getTime().toString().slice(0, -3)) + '|' + getTiCookieByName('tiSessionID') + '|' + getTiCookieByName('_ga'), 'binary').toString('base64');
          let url = 'https://www.ti.com.cn/store/ti/zh/cart?contShopUrl=https%3A%2F%2Fwww.ti.com.cn%2F%3Flogin-check%3Dtrue&_ticdt='+_ticdt;          

          let gocartcmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    ${url} `;

          ret = await syncExec(gocartcmdStr);

          if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }else{
            const msg = `跳到购物车`;
              logger(msg);
          }

          url = 'https://www.ti.com.cn/store/ti/zh/cart/checkout';

           gocartcmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    ${url} `;

          ret = await syncExec(gocartcmdStr);

          if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }else{
              const msg = `结算`;
              logger(msg);
          }

          url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy';

           gocartcmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    ${url} `;

          ret = await syncExec(gocartcmdStr);

          if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }else{
              const msg = `购买`;
              logger(msg);
          }

          url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi';

           gocartcmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    ${url} `;

          ret = await syncExec(gocartcmdStr);

          if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }else{
              const msg = `购买确认`;
              logger(msg);
          }

          url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-address/add?storeFlashAtts=true&validPrice=true';

           gocartcmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    ${url} `;

          ret = await syncExec(gocartcmdStr);

          if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }else{
              const msg = `访问地址`;
              logger(msg);
          }

          url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-address/addSelected';
          let pdata = 'addressType=Business&countryIso=CN&editAddress=true&addressId=9116518350871&shippingAddress=true&firstName=Yutao&lastName=Zhang&line1=Room+3C078%2C+3+%2F+F%2C+Jiahe+HuaqiangBu&line2=ilding%2C+Huaqiang+North+Shennan+Midd&townCity=Shenzhen+City&state=Guangdong+Province&gstn=&panNumber=&sezCustomer=&postcode=518000&companyName=jinhangtaoElectronicTechnology+Co.%2C&companyUrl=https%3A%2F%2Fwww.fy35.com%2Fcompany%2F1311148.html&gstExemptCert=&pstExemptCert=&qstExemptCert=&taxId=&phoneCountryPrefix=86-CN&phoneNumber=137+1379+2562&phoneExtension=&email=hlmp%40szcxrdz.com&_saveInAddressBook=on&middleName2=Shenzhen&taxExemptValidated=false&isTaxExempt=false&same_billingAddress=on&billingAddress=true&CSRFToken=6c7d40aa-99c7-4511-a32b-3f485058462c';
           gocartcmdStr = `curl --compressed \
                    -H 'Host: www.ti.com.cn' \
                    -H 'Connection: keep-alive' \
                    -H 'sec-ch-ua: "Google Chrome";v="${chromeVer}", "Chromium";v="${chromeVer}", ";Not A Brand";v="99"' \
                    -H 'sec-ch-ua-mobile: ?0' \
                    -H "User-Agent: ${ua}" \
                    -H "Content-Type: application/json" \
                    -H 'X-Sec-Clge-Req-Type: ajax' \
                    -H 'Expires: 0' \
                    -H "Cache-Control: no-store, must-revalidate" \
                    -H 'sec-ch-ua-platform: ${platform}' \
                    -H 'Accept: */*' \
                    -H 'Origin: https://www.ti.com.cn' \
                    -H 'Sec-Fetch-Site: same-origin' \
                    -H 'Sec-Fetch-Mode: cors' \
                    -H 'Sec-Fetch-Dest: empty' \
                    -H 'Referer: ${referer}' \
                    -H 'Accept-Encoding: gzip, deflate, br' \
                    -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
                    -H 'Cookie: ${cookie}' \
                    -d '${pdata}' \
                    ${url} `;

          ret = await syncExec(gocartcmdStr);

          if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
              logger("全查方案：请在后台更换cookie");
          }else{
              const msg = `提交地址`;
              logger(msg);
          }

          https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-address/addSelected




      } catch(e) {
          logger(e);
      }
                               
})();
